import { storage } from '@/config/index';
import { getList } from '@/api/tenant/channel/TenantChannelManagementApi';
import type { TenantChannelModel } from '@/api/tenant/channel/TenantChannelManagementApi';

// 缓存前缀
const cachePrefix = 'opsli:channel';

// 渠道项接口
export interface ChannelItem {
    id: string;
    name: string;
    remark?: string;
    [key: string]: any;
}

/**
 * 获得前端本地缓存
 */
function getCache(): ChannelItem[] | null {
    let cache: string | null = null;

    if (storage === 'localStorage') {
        cache = localStorage.getItem(cachePrefix);
    } else if (storage === 'sessionStorage') {
        cache = sessionStorage.getItem(cachePrefix);
    } else {
        cache = localStorage.getItem(cachePrefix);
    }

    return cache ? JSON.parse(cache) : null;
}

/**
 * 设置前端本地缓存
 */
function setCache(channelList: ChannelItem[]): void {
    const json = JSON.stringify(channelList);

    if (storage === 'localStorage') {
        localStorage.setItem(cachePrefix, json);
    } else if (storage === 'sessionStorage') {
        sessionStorage.setItem(cachePrefix, json);
    } else {
        localStorage.setItem(cachePrefix, json);
    }
}

/**
 * 移除缓存
 */
function removeCache(): void {
    if (storage === 'localStorage') {
        localStorage.removeItem(cachePrefix);
    } else if (storage === 'sessionStorage') {
        sessionStorage.removeItem(cachePrefix);
    } else {
        localStorage.removeItem(cachePrefix);
    }
}

/**
 * 从服务器更新渠道列表
 */
export async function updateChannelList(): Promise<ChannelItem[]> {
    try {
        const { data } = await getList({
            pageNo: 1,
            pageSize: 1000 // 获取足够多的数据
        });

        if (data && data.rows) {
            const channelList: ChannelItem[] = data.rows.map((item: TenantChannelModel) => ({
                id: item.id!,
                name: item.name!,
                remark: item.remark
            }));

            setCache(channelList);
            return channelList;
        }

        return [];
    } catch (error) {
        console.error('获取渠道列表失败:', error);
        return [];
    }
}

/**
 * 获取渠道列表 - 同步版本（仅从缓存获取）
 */
export function getChannelListSync(): ChannelItem[] {
    let cache = getCache();
    if (!cache) {
        console.log('远程更新渠道列表');
        updateChannelList().then(r => { });
        return [];
    }

    return cache || [];
}

/**
 * 获取渠道列表
 */
export async function getChannelList(): Promise<ChannelItem[]> {
    let cache = getCache();

    // 如果本地缓存没有，则去远端获取
    if (!cache || cache.length === 0) {
        return await updateChannelList();
    }

    return cache || [];
}

/**
 * 根据渠道ID获取渠道名称
 */
export async function getChannelNameById(channelId: string): Promise<string | null> {
    const channelList = await getChannelList();
    const channel = channelList.find(item => item.id === channelId);
    return channel ? channel.name : null;
}

/**
 * 根据渠道名称获取渠道ID
 */
export async function getChannelIdByName(channelName: string): Promise<string | null> {
    const channelList = await getChannelList();
    const channel = channelList.find(item => item.name === channelName);
    return channel ? channel.id : null;
}

/**
 * 同步根据渠道ID获取渠道名称（从缓存）
 */
export function getChannelNameByIdSync(channelId: string): string | null {
    const channelList = getChannelListSync();
    const channel = channelList.find(item => item.id === channelId);
    return channel ? channel.name : null;
}

/**
 * 同步根据渠道名称获取渠道ID（从缓存）
 */
export function getChannelIdByNameSync(channelName: string): string | null {
    const channelList = getChannelListSync();
    const channel = channelList.find(item => item.name === channelName);
    return channel ? channel.id : null;
}

/**
 * 清空渠道缓存
 */
export function clearChannelList(): void {
    removeCache();
}

/**
 * 预加载渠道数据
 */
export async function preloadChannelList(): Promise<void> {
    await getChannelList();
}

// 渠道工具类
export class ChannelUtils {
    /**
     * 获取渠道列表
     */
    static async getChannelList(): Promise<ChannelItem[]> {
        return getChannelList();
    }

    /**
     * 根据渠道ID获取渠道名称
     */
    static async getChannelNameById(channelId: string): Promise<string | null> {
        return getChannelNameById(channelId);
    }

    /**
     * 根据渠道名称获取渠道ID
     */
    static async getChannelIdByName(channelName: string): Promise<string | null> {
        return getChannelIdByName(channelName);
    }

    /**
     * 清空渠道缓存
     */
    static clearChannelList(): void {
        clearChannelList();
    }
} 